import { reqLogin, reqGetUserInfo, reqGetUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login({ commit }, loginFrom) {
    const { data: token } = await reqLogin(loginFrom)
    commit('setToken', token)
  },
  async getUserInfo({ commit }) {
    const { data: data1 } = await reqGetUserInfo() // 获取用户基本数据
    const { data: data2 } = await reqGetUserDetailById(data1.userId) // 获取用户头像
    const data = {
      ...data1,
      ...data2
    }
    commit('setUserInfo', data)
    return data
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
